package com.elinkway.infinitemovies.service;


import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.download.ContainSizeManager;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadJobListener;
import com.elinkway.infinitemovies.download.DownloadProvider;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.Utils;

import java.util.Timer;
import java.util.TimerTask;


@SuppressLint("NewApi")
public class DownloadService extends Service {

    public static final String ACTION_ADD_TO_DOWNLOAD = "add_to_download";

    public static final String EXTRA_MEDIAITEM_ENTRY = "download_entity";

    public static final String CHECK_SDCARD_FREESIZE = "check_sdcard_freesize";

    NotificationManager mNotificationManager = null;

    private DownloadProvider mDownloadProvider;

    private Timer mTimer;

    private ContainSizeManager mSizeManager;
    //private static final int DOWNLOAD_NOTIFY_ID = 667668;
    private Notification n;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mDownloadProvider = MoviesApplication.getInstance().getDownloadManager().getProvider();
        mSizeManager = new ContainSizeManager();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null) {
            String action = intent.getAction();
//			LogUtils.e("dyf", "进入服务----"+action);
            if (action.equals(ACTION_ADD_TO_DOWNLOAD)) {
                DownloadEntity entry = (DownloadEntity) intent.getSerializableExtra(EXTRA_MEDIAITEM_ENTRY);
                addToDownloadQueue(entry, startId);
                //每次添加新的下载，都开启sd卡检查
                if (null != mTimer) {
                    mTimer.cancel();
                }

                startCheckSDCard();
            }
            if (action.equals(CHECK_SDCARD_FREESIZE)) {
                if (null != mTimer) {
                    mTimer.cancel();
                }

                startCheckSDCard();
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void addToDownloadQueue(DownloadEntity entry, int startId) {

        String downloadPath = StringUtil.isEmpty(entry.getPath()) ? DownloadHelper.getDownloadPath() : entry.getPath();
        DownloadJob downloadJob = new DownloadJob(entry, downloadPath);
        downloadJob.setIndex(entry.getIndex());
        if (mDownloadProvider.queueDownload(downloadJob)) {
            downloadJob.setListener(mDownloadJobListener);
            //downloadJob.notifyDownloadStarted();
            downloadJob.start();
        }
    }

    public void startCheckSDCard() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mDownloadProvider.getQueuedDownloads().size() != 0) {
                    if (mSizeManager.getFreeSize() <= Utils.SDCARD_MINSIZE) {
                        Intent intent = new Intent();
                        intent.setAction(Utils.SDCARD_NOSPACE_ACTION);
                        sendBroadcast(intent);
                        mTimer.cancel();
                    }
                } else {
                    mTimer.cancel();
                }


            }
        }, 10000, 10000);
    }

    /**
     * do some action
     */
    private Handler doActionHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msgId = msg.what;
            switch (msgId) {
                case 1:
                    ToastUtil.showShortToast(getApplicationContext(), "no");
//                	mTimer.cancel();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private DownloadJobListener mDownloadJobListener = new DownloadJobListener() {

        @Override
        public void downloadEnded(DownloadJob job) {
            LogUtils.i("dyf", "下载成功：downloadEnded");
            String displayName = job.getEntity().getDisplayName();
            Toast.makeText(
                    DownloadService.this,
                    displayName + " 已下载完成",
                    Toast.LENGTH_SHORT).show();
            mDownloadProvider.downloadCompleted(job);
            int uncompleteCount = mDownloadProvider.getQueuedDownloads().size();
            if (uncompleteCount == 0) {
                if (null != mTimer)
                    mTimer.cancel();
                stopSelf();
            }

        }

        @Override
        public void downloadStarted(DownloadJob job) {
            // TODO Auto-generated method stub

        }

        @Override
        public void downloadPaused(DownloadJob job) {
            // TODO Auto-generated method stub

        }

        @Override
        public void downloadOnDownloading(DownloadJob job) {
            // TODO Auto-generated method stub

        }

        @Override
        public void updateNotifyOnDownloading(DownloadJob job) {
            // TODO Auto-generated method stub

        }

        @Override
        public void downloadOnPause(DownloadJob job) {
            if (job == null)
                return;
            //notifications.remove(job.getNotifyIdByHashId());
            //mNotificationManager.cancel(job.getNotifyIdByHashId());
            mNotificationManager.cancel((int) job.getTotalSize()); // 删除下载完成的任务时，清除相应的下载完成通知提示
        }

        private void playFromNotify(Context context, String path, String name,
                                    String size, double downPercent, DownloadJob job, int notifyId) {

            if (null == job || null == job.getEntity()) {
                return;
            }
        }

    };


}
